package cool.tianyou.blue.bird.module.synchronize.service;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONObject;
import cool.tianyou.blue.bird.common.model.contstant.DeviceMessageEnum;
import cool.tianyou.blue.bird.common.model.po.Device;
import cool.tianyou.blue.bird.common.tool.LocalCache;
import cool.tianyou.blue.bird.common.util.RandomUtil;
import cool.tianyou.blue.bird.model.DeviceMessage;
import java.util.HashMap;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

/**
 * MQ消息发送服务
 *
 * @author 刘天佑
 * @date 2021-09-01
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class JmsService {

  private final JmsTemplate jmsTemplate;
  private final String TOPIC_PREFIX = "DOVE";
  private final String SLASH = ".";
  private final LocalCache localCache;

  public void sendMessage(Integer userId, Object message) {
    localCache.allUsers()
        .stream()
        .filter(user -> Objects.equals(userId, user.getUserId()))
        .forEach(user -> {
          try {
            ActiveMQTopic topic = new ActiveMQTopic(genTopic(userId, user.getToken()));
            jmsTemplate.convertAndSend(topic, JSONObject.toJSONString(message));
            log.info("MQTT消息推送：topic：[{}] ,deviceId:[{}]", topic.getTopicName(),
                user.getDeviceId());
          } catch (Exception e) {
            log.error("推送消息失败：userId：[{}] ,deviceId:[{}]", userId, user.getDeviceId(), e);
          }
        });
  }


  /**
   * 发送更新秘钥的消息
   *
   * @param fromDevice 消息来源设备
   */
  public void sendUpdatePublicKeyMessage(Device fromDevice) {
    DeviceMessage deviceMessage = DeviceMessage.builder()
        .messageId(RandomUtil.uuid())
        .type("设备更新秘钥").fromDevice(fromDevice.getAlias())
        .build();
    sendMessage(fromDevice.getUserId(), deviceMessage);
  }

  /**
   * 发送设备请求解锁的消息
   *
   * @param device 待解锁的设备
   */
  public void sendRequestUnlockMessage(Device device) {
    DeviceMessage deviceMessage = DeviceMessage.builder()
        .messageId(RandomUtil.uuid())
        .type(DeviceMessageEnum.REQUEST_UNLOCK.name())
        .fromDevice(device.getAlias())
        .data(MapBuilder.create(new HashMap<String, Object>())
            .put("deviceId", device.getId())
            .put("alias", device.getAlias())
            .map())
        .build();
    sendMessage(device.getUserId(), deviceMessage);
  }


  /**
   * 登录成功消息
   *
   * @param fromDevice  消息来源设备
   * @param isNewDevice 是否是新设备
   */
  public void loginSuccessMessage(Device fromDevice, Boolean isNewDevice) {
    DeviceMessage deviceMessage = DeviceMessage.builder()
        .messageId(RandomUtil.uuid())
        .type((isNewDevice ? "新" : "") + "设备上线").fromDevice(fromDevice.getAlias())
        .build();
    sendMessage(fromDevice.getUserId(), deviceMessage);
  }


  private String genTopic(Integer userId, String token) {
    return TOPIC_PREFIX + SLASH + userId + SLASH + MD5.create().digestHex16(token);
  }


}
